const mongoose = require("../db");
const schema = new mongoose.Schema({
  routerPath: String,
  routerName: String,
  componentPath: String,// /src/views/xxx.vue
  menuName: String,
  menuIcon: String,
  menuType: Number,//1 目录 2菜单 3按钮 4外链
  menuSort: Number,
  perId: String,//sys:user:add  sys:user:edit  sys:user:delete  sys:user:view 权限标识
  menuParentId: { type: mongoose.Schema.Types.ObjectId, ref: 'Menu' },
  status: { type: Number, default: 1 }, // 1启用 0禁用
  children: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Menu' }]
});

schema.statics.getMenuTree = async function() {
  // 查找所有的顶级菜单
  const topMenus = await this.find({ menuParentId: null });
  console.log(topMenus.map(v=>v.menuName),'topMenus');
  console.log(JSON.stringify(topMenus,null,2),'topMenus');

  const buildTree = async (menu) => {

    // 查找当前菜单的所有子菜单
    const children = await this.find({ menuParentId: menu._id });
    console.log(menu.menuName+'的孩子有',children.length,'个');
    console.log(menu.menuName+'的孩子有',children.map(v=>v.menuName),'个');
    if (children.length > 0) {
      // menu.children = children;
      // await Promise.all(children.map(child => buildTree(child)));

      // 如果有子菜单，递归构建子菜单树
      menu.children = await Promise.all(children.map(child => buildTree(child)));
    }
    return menu;
  };
  
  return Promise.all(topMenus.map(menu => buildTree(menu)));
};

module.exports = mongoose.model("Menu", schema);
